package org.example.volunteerend.controller;

import java.util.List;
import java.util.Map;

import org.example.volunteerend.dto.PointsRecordRequest;
import org.example.volunteerend.dto.Result;
import org.example.volunteerend.service.PointsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
public class PointsController {

    private final PointsService pointsService;
    
    @Autowired
    public PointsController(PointsService pointsService) {
        this.pointsService = pointsService;
    }
    
    /**
     * 添加积分记录
     */
    @PostMapping("/points-records")
    public Result<Map<String, Object>> addPointsRecord(
            @RequestBody PointsRecordRequest request,
            HttpServletRequest httpRequest) {
        
        // 从JWT获取用户ID
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或登录已过期");
        }
        
        try {
            // 添加积分记录
            Map<String, Object> data = pointsService.addPointsRecord(request, userId);
            
            return Result.success("积分添加成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("积分添加失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取积分排行榜
     */
    @GetMapping("/points/ranking")
    public Result<List<Map<String, Object>>> getPointsRanking(
            @RequestParam(required = false) Integer limit) {
        
        try {
            // 获取积分排行榜
            List<Map<String, Object>> data = pointsService.getPointsRanking(limit);
            
            return Result.success("success", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取积分排行榜失败：" + e.getMessage());
        }
    }
} 